<?php
namespace app\process;

use Workerman\Timer;
use Workerman\Worker;
use support\Log;
use Webman\RedisQueue\Redis;
use support\Db;

class BatchProcessor
{
    public function onWorkerStart(Worker $worker)
    {
        // 每10秒执行一次
        Timer::add(2, function() {
            $this->processBatch();
        });
    }
    
    protected function processBatch()
    {
        // 批处理逻辑 
        Log::info("buy3000w本地跑批抓包: 耗时：".date("Y-m-d H:i:s")); 
        $hour = date('H');//9;
        $minute = date('i'); //43;   
        try{
        	// 业务逻辑
//         	if(in_array(date('w'), [6,0])){
//         		$msg =  date('Y-m-d H:i:s')."---周末无需跑！\r\n";
//         		throw new \Exception($msg);
//         	}
//         	if($hour != 9 ){
//         		$msg = date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n"; 
// 				throw new \Exception($msg);
// 			}
// 			if($hour == 9 && $minute < 30){ 
// 				$msg = date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";
// 				throw new \Exception($msg);
// 			}
			
	        $okKey = 'buy3000w:ok:'.date("Y-m-d");
	        if(Redis::exists($okKey)){ 
	        	$msg = date('Y-m-d H:i:s')."---".$hour.':'.$minute.",今日已经购买了 无许再跑批\r\n";
	        	throw new \Exception($msg);
	        }
	        self::do_run();
			
        } catch (\Exception $e) {
        	// 系统异常处理
        	echo $e->getMessage();
        }
//         if(in_array(date('w'), [6,0])){
// 			echo date('Y-m-d H:i:s')."---周末无需跑！\r\n";exit;
// 			throw new ApiException('自定义异常');
// 		}
// 		if($hour != 9 ){
// 			echo date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
// 		}
// 		if($hour == 9 && $minute < 30){
// 			echo  date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
// 		}
//         	//         	if($hour == 15 && $minute > 2){
//         	//         		echo  date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
//         	//         	}
//         	//         	if($hour == 11 && $minute > 30 ){
//         	//         		echo  date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
//         	//         	}
//         	//         	if($hour == 12){
//         	//         		echo  date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
//         	//         	}
        
        
//         $the_date = date('Y-m-d');
//         $start_time =  microtime(true);
//         $last_minute = date('i'); //分钟
//         $last_seconds = date('s'); //秒
//         $i = 1;
//         $redis = new \Redis ();
//         $redis->connect ( '127.0.0.1', '6379' );
//         $redis->auth ( 'Sycs0PrusIuDkMNQ' );
        
//         $okKey = 'buy3000w:ok:'.date("Y-m-d");
//         if($redis->exists($okKey)){
//         	echo  date('Y-m-d H:i:s')."---".$hour.':'.$minute.",今日已经购买了 无许再跑批\r\n";exit;
//         }
        
//         $sleep_time = 1;
//         $begin = microtime(true);
//         while(($last_minute == $minute) && ($last_seconds < 59)){
//         	self::do_run($redis);
//         	$last_minute = date('i');
//         	$last_seconds = date('s');
//         	echo "--------------------------------------------当前时间".date('Y-m-d H:i:s')."第{$i}次处理 睡眠".$sleep_time."秒，处理中\r\n";
//         	sleep($sleep_time);
//         	$i++;
//         }
//         $used_time = microtime(true) - $begin;
//         echo "--------------------------------------------当前时间".date('Y-m-d H:i:s')."用时".$used_time."秒，处理成功\r\n";
// //         if($hour < 9 || $hour >= 15 ){
// //             echo date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
// //         }
// //         if($hour == 9 && $minute < 25){
// //             echo  date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
// //         }
// //         if($hour == 11 && $minute > 30 ){
// //             echo  date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
// //         }
// //         if($hour == 12){
// //             echo  date('Y-m-d H:i:s')."---".$hour.':'.$minute.",时间段不允许\r\n";exit;
// //         }  
// //         $url = "http://127.0.0.1:8787/index/json";
// //         Log::info(file_get_contents($url));
// 		echo date("Y-m-d H:i:s")."\r\n"; 
        
    }
    
    /**
     * 爬取数据
     * @param unknown $page
     */
    public static function do_run($redis)
    {
    	$page = 1;
    	$money = 30000000; //三千万
    	$min_rise_fall = 1; //涨幅小于3
    	$end = false;
    	$the_date = date('Y-m-d');
    	while ($end == false){
    		$url = "https://push2.eastmoney.com/api/qt/clist/get?fid=f62&po=1&pz=50&pn=$page&np=1&fltt=2&invt=2&ut=b2884a393a59ad64002292a3e90d46a5&fs=m%3A0%2Bt%3A6%2Bf%3A!2%2Cm%3A0%2Bt%3A13%2Bf%3A!2%2Cm%3A0%2Bt%3A80%2Bf%3A!2%2Cm%3A1%2Bt%3A2%2Bf%3A!2%2Cm%3A1%2Bt%3A23%2Bf%3A!2%2Cm%3A0%2Bt%3A7%2Bf%3A!2%2Cm%3A1%2Bt%3A3%2Bf%3A!2&fields=f12%2Cf14%2Cf2%2Cf3%2Cf62%2Cf184%2Cf66%2Cf69%2Cf72%2Cf75%2Cf78%2Cf81%2Cf84%2Cf87%2Cf204%2Cf205%2Cf124%2Cf1%2Cf13";
    		//$url = "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112307500466123838297_1745543193449&fid=f62&po=1&pz=50&pn=$page&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=m%3A0%2Bt%3A6%2Bf%3A!2%2Cm%3A0%2Bt%3A13%2Bf%3A!2%2Cm%3A0%2Bt%3A80%2Bf%3A!2%2Cm%3A1%2Bt%3A2%2Bf%3A!2%2Cm%3A1%2Bt%3A23%2Bf%3A!2%2Cm%3A0%2Bt%3A7%2Bf%3A!2%2Cm%3A1%2Bt%3A3%2Bf%3A!2&fields=f12%2Cf14%2Cf2%2Cf3%2Cf62%2Cf184%2Cf66%2Cf69%2Cf72%2Cf75%2Cf78%2Cf81%2Cf84%2Cf87%2Cf204%2Cf205%2Cf124%2Cf1%2Cf13";
    		$response = curlProxyGet($url);
    		//     		$jsonStart = strpos($jsonp, '(') + 1;
    		//     		$jsonEnd = strrpos($jsonp, ')');
    		//     		$jsonLength = $jsonEnd - $jsonStart;
    		//     		$response = substr($jsonp, $jsonStart, $jsonLength);
    		//var_dump($response);
    		echo "[".$page."]\r\n";
    		$result_data = json_decode($response, true);
    		$datas = $result_data['data']['diff'];
    		foreach ($datas as $key => $data){
    			$code = substr($data['f12'], 0, 2);
    			$top = 50 * ($page -1) + $key + 1;
    			$gp_code = $data['f12'];
    			$gp_name = $data['f14'];
    			$price  =  ($data['f2']== '-') ? 0 : $data['f2'];
    			$rise_fall = ($data['f3']== '-') ? 0 : $data['f3'];
    			$zljlr_je  =  ($data['f62']== '-') ? 0 : $data['f62'];
    			$zljlr_jzb =  ($data['f184']== '-') ? 0 : $data['f184'];
    			if (strpos($gp_name, 'N') !== false) {
    				//不买新股
    			}else if (strpos($gp_name, 'ST') !== false) {
    				//不买退市票
    			}else if (strpos($gp_name, 'C') !== false) {
    				//不买次新股
    			}else if (strpos($gp_name, '银行') !== false) {
    				//不买银行
    			}else{
    				if($data['f62'] > $money && $data['f3'] <= $min_rise_fall
    						&& $price >= 5 && $price <= 50 && !in_array($code, ['20','90','68'])){
    							$sanqianwanKey = "buy3000wGupiao:the_date:".$the_date.":gp_code:".$gp_code;
    							if(!$redis->exists($sanqianwanKey)){
    								$insert_data  = [
    										'the_date' => $the_date,
    										'top' => $top,
    										'gp_code' => $gp_code,
    										'gp_name' => $gp_name,
    										'price' => $price,
    										'rise_fall' => $rise_fall,
    										'zljlr_je' => $zljlr_je,
    										'zljlr_jzb' => $zljlr_jzb,
    										'create_time' => date('Y-m-d H:i:s')
    								];
    								$flag = self::buy3000w(2);
    								if($flag){
    									//按照指定价格购买
    									self::buy_gupiao_by_price($redis, $insert_data, 10000, 'buy3000w');
    								}else{
    									$okKey = 'buy3000w:ok:'.date("Y-m-d");
    									$redis->set($okKey, date("Y-m-d H:i:s"));
    								}
    								$redis->set($sanqianwanKey, date("Y-m-d H:i:s"));
    								$redis->expire($sanqianwanKey, 12*60*60);
    							}
    				}
    			}
    			
    		}
    		//二位数组最后一个数组
    		$end_data = end($datas);
    		if($end_data['f62'] < $money){
    			$end = true;
    		}
    		$page++;
    	}
    }
    
    /**
     * 请求curl
     * @param unknown $url
     * @return unknown
     */
    public static function curlProxyGet($url){
    	$proxyInfo = Db::name("gp_proxy")->where(['is_open' => 1])->orderRaw('rand()')->find();
    	if(!empty($proxyInfo)){
    		$proxy = $proxyInfo['ip'].":".$proxyInfo['port'];
    		$res = Db::name("gp_proxy")->where(['id' => $proxyInfo['id']])->inc("times", 1)->update(['update_time' => time()]);
    	}else{
    		$proxy = "119.84.46.227:5566"; // 代理IP:端口
    	}
    	echo $proxy."\r\n";
    	$ch = curl_init();
    	//     $xforip = rand ( 1, 254 ) . "." . rand ( 1, 254 ) . "." . rand ( 1, 254 ) . "." . rand ( 1, 254 );
    	//     echo "【".$xforip."】\r\n";
    	//     $header [] = "X-FORWARDED-FOR: $xforip";
    	//     $header [] = "CLIENT-IP: $xforip";
    	//     curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
    	curl_setopt ($ch, CURLOPT_URL, $url);
    	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 2);
    	curl_setopt($ch, CURLOPT_PROXY, $proxy); // 设置代理
    	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,1);
    	curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
    	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
    	curl_setopt($ch, CURLOPT_REFERER, "https://data.eastmoney.com/zjlx/detail.html");
    	$res = curl_exec($ch); echo $res;
    	if (curl_errno($ch)) {
    		curl_close($ch);
    		Db::name("gp_proxy")->where(['id' => $proxyInfo['id']])->inc("err_times", 1)->update(['is_delete' => 1, 'update_time' => time()]);
    		return curlProxyGet($url);
    	}
    	curl_close($ch);
    	return $res;
    }
}